package com.qcit.user.bean.common

import com.google.gson.Gson
import com.itkacher.okhttpprofiler.OkHttpProfilerInterceptor
import com.qcit.common.api.BaseAPI
import com.qcit.common.net.Config
import com.qcit.common.net.Level
import com.qcit.common.net.LoggingInterceptor
import com.qcit.older.usercenter.common.QRequesterAuthInterceptor
import com.qcit.older.usercenter.common.QRequesterLogInterceptor

import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create

class QRequester {
    companion object {
         fun <T> getService(baseUrl: String, service: Class<T>): T {

            var builder = OkHttpClient.Builder()
                .addInterceptor(QRequesterAuthInterceptor())
                //.addInterceptor(HttpHeaderInterceptor())
                .addInterceptor(
                    LoggingInterceptor
                        .Builder()//构建者模式
                    .loggable(true) //是否开启日志打印
                    .setLevel(Level.BASIC) //打印的等级
                    .log(Platform.INFO) // 打印类型
                    .request("lib093") // request的Tag
                    .response("lib093")// Response的Tag
                    //.addHeader("log-header", "I am the log request header.") // 添加打印头, 注意 key 和 value 都不能是中文
                    .build()
                )
            if(Config.DEBUG){
                builder.addInterceptor(QRequesterLogInterceptor())
                builder.addInterceptor(OkHttpProfilerInterceptor())
            }

            var clien=builder.build()
            val retrofit = Retrofit.Builder().baseUrl(baseUrl)
                //格式转换
                .addConverterFactory(GsonConverterFactory.create())
                //正常的retrofit返回的是call，此方法用于将call转化成Rxjava的Observable或其他类型
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(clien)
                .build()
            return retrofit.create(service)
        }

        //可用于多种不同种类的请求
        inline fun<reified T> instan(): T {
            return getService(BaseAPI.BASE_URL, T::class.java)
        }

        inline fun<reified T> instan(url: String): T {
            return getService(url, T::class.java) as T
        }
    }
}

